package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.course.CourseDTO;
import com.qk.entity.Course;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: Enid
 * @date: 2025/10/9 16:35
 * @description:
 * MybatisPlus的实现，mapper接口有默认的实现
 */
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Override
    public PageResult<Course> list(CourseDTO courseDTO) {
        PageHelper.startPage(courseDTO.getPage(),courseDTO.getPageSize());
        List<Course> result = courseMapper.list(courseDTO);
        Page<Course> page = (Page<Course>) result;
        return PageResult.<Course>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addCourse(Course course) {

        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.insert(course);
    }

    @Override
    public Course selectById(Integer id) {
        return courseMapper.selectById(id);
    }

    @Override
    public void deleteById(Integer id) {
        courseMapper.deleteById(id);
    }

    @Override
    public List<Course> all() {
        return courseMapper.selectList(null);
    }

    @Override
    public List<Course> listBySubject(String subject) {
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        if(!ObjectUtil.isEmpty(subject))
            queryWrapper.eq(Course::getSubject,subject);
        return courseMapper.selectList(queryWrapper);
    }


    @Override
    public void update(Course course) {
        boolean hasNullField = BeanUtil.hasNullField(course, "id","description", "updateTime", "createTime");
        if (hasNullField){
            throw new RuntimeException("参数错误");
        }
        course.setUpdateTime(LocalDateTime.now());
        courseMapper.updateById(course);
    }
}
